<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :xs="15" :sm="18" :md="19" :lg="20" :xl="20">
        <!--工具栏-->
        <div class="head-container">
          <div v-if="crud.props.searchToggle">
            <!-- 搜索 -->
            <el-input
              v-model="query.blurry"
              clearable
              size="small"
              placeholder="输入昵称进行搜索"
              style="width: 200px;"
              class="filter-item"
              @keyup.enter.native="crud.toQuery"
            />
            <el-select
              v-model="query.state"
              clearable
              size="small"
              placeholder="状态"
              class="filter-item"
              style="width: 90px"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in enabledTypeOptions"
                :key="item.key"
                :label="item.display_name"
                :value="item.key"
              />
            </el-select>
            <rrOperation/>
          </div>
          <crudOperation show="" :permission="permission"/>
          <!--自定义导入-->
          <el-button
            class="filter-item"
            size="mini"
            type="warning"
            icon="el-icon-download">
            <a :href=" path+ '用户导入模板.xlsx'" download="用户导入模板.xlsx" style="color: #fff;">下载模板</a>
          </el-button>
          <el-upload
            :headers="headers"
            :action="'/admin/sysUser/import-user-list'"
            :on-remove="fileRemove"
            :before-upload="beforeUpload"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            multiple
            :file-list="fileList"
          >
            <el-button
              v-if="crud.optShow.download"
              :loading="crud.downloadLoading"
              class="filter-item"
              size="mini"
              type="warning"
              icon="el-icon-download"
            >导入人员</el-button>
          </el-upload>


  </div>
        <!--表单渲染-->
        <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU"
                   :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="570px">
          <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="66px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户名" prop="name">
                  <el-input v-model="form.name"/>
                </el-form-item>
                <el-form-item label="昵称" prop="userName">
                  <el-input v-model="form.userName"/>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                  <el-input v-model.number="form.phone"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="密码" prop="password">
                  <el-input v-model="form.password" type="password"/>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="form.email"/>
                </el-form-item>
                <el-form-item label="状态">
                  <el-radio-group v-model="form.state">
                    <el-radio v-model="form.state" :label="false">未冻结</el-radio>
                    <el-radio v-model="form.state" :label="true">冻结</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item style="margin-bottom: 0;" label="角色" prop="role">
              <el-select
                v-model="form.roleIdList"
                style="width: 437px"
                multiple
                placeholder="请选择"
                @remove-tag="deleteTag"
                @change="changeRole"
              >
                <el-option
                  v-for="item in roles"
                  :key="item.id"
                  :label="item.roleDescribe"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table ref="table" v-loading="crud.loading" :data="crud.data" style="width: 100%;"
                  @selection-change="crud.selectionChangeHandler">
          <el-table-column :selectable="checkboxT" type="selection" width="55"/>
          <el-table-column :show-overflow-tooltip="true" prop="name" label="用户名"/>
          <el-table-column :show-overflow-tooltip="true" prop="userName" label="昵称"/>
          <el-table-column :show-overflow-tooltip="true" prop="phone" width="100" label="电话"/>
          <el-table-column :show-overflow-tooltip="true" width="135" prop="email" label="邮箱"/>
          <el-table-column label="是否冻结" align="state" prop="state">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.state"
                active-color="#13ce66"
                inactive-color="#E9EBEF"
                @change="changeEnabled(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="createTime" width="135" label="创建日期">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-permission="['admin','user:edit','user:del']"
            label="操作"
            width="115"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <udOperation
                :data="scope.row"
                :permission="permission"
                :disabled-dle="scope.row.id === user.id"
              />
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <pagination/>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudUser from '@/api/system/user'
import { isvalidPhone } from '@/utils/validate'
import { getRoleList } from '@/api/system/role'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import DateRangePicker from '@/components/DateRangePicker/index'
import Treeselect from '@riophae/vue-treeselect'
import { mapGetters } from 'vuex'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import appUtils from '@/utils/appUtils'
import { getToken } from '@/utils/auth'
import store from '@/store'
import {frozenUser} from '@/api/system/user'

let userRoles = []
const defaultForm = {
  name: null,
  id: null,
  userName: null,
  state: false,
  email: null,
  /*默认状态未冻结*/
  roleIdList: [],
  phone: null,
  password: null
}
export default {
  name: 'User',
  components: { Treeselect, crudOperation, rrOperation, udOperation, pagination, DateRangePicker },
  cruds() {
    return CRUD({ title: '用户', url: 'admin/sysUser/page', exportUrl:'admin/sysUser/export-user-list',crudMethod: { ...crudUser } })
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  // 数据字典
  data() {
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      /*下载路径*/
      path: process.env.BASE_URL,
      /*上传文件的列表*/
      fileList:[],
      headers: {
        'Authorization': getToken()
      },
      showUpload: false,
      height: document.documentElement.clientHeight - 180 + 'px;',
      deptName: '',  level: 3,
      roles: [],
      roleIdList: [], // 多选时使用
      defaultProps: { children: 'children', label: 'name', isLeaf: 'leaf' },
      permission: {
        add: [ 'sys_user_view'],
        edit: [ 'sys_user_view'],
        del: [ 'sys_user_view']
      },
      enabledTypeOptions: [
        { key: 'false', display_name: '未冻结' },
        { key: 'true', display_name: '冻结' }
      ],
      rules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入用户真是姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, trigger: 'blur', validator: validPhone }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'minioApi',
      'updateAvatarApi',
      'baseApi'
    ])
  },
  created() {
    this.getAllRoles()
  },
  mounted: function() {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
  },
  methods: {
    /*删除上传文件*/
    fileRemove(file, fileList){

    },
    /*文件上传之前*/
    beforeUpload(file){
      crud.downloadLoading=true
      /*限定导入格式*/
        let format=(file.name).substring(file.name.lastIndexOf("."),file.name.length)
      if (format!=='xlsx'){
        appUtils.showError("上传错误，只能上传.xlsx格式的文件")
        return false;
      }
    },
    /*文件上传成功之后*/
    uploadSuccess(res, file, fileList){
      crud.downloadLoading=true
      if (res.state){
        appUtils.showSuccess("导入成功,未导入数据："+res.data.errorList.length+"条")
        this.fileList=[]
        this.crud.refresh()
      }
      else {
        this.fileList=[]
        appUtils.showError(res.msg)
      }
    },
    /*文件上传失败*/
    uploadError(err, file, fileList){
      crud.downloadLoading=true
      appUtils.showError(err.msg)
      this.fileList=[]
    },
    /*展示上传头像*/
    toggleShow() {
      this.showUpload = true
    },
    /*头像上传成功*/
    cropUploadSuccess(jsonData, field) {
      store.dispatch('GetInfo').then(() => {
      })
    },
    changeRole(value) {
      var that = this
      value.forEach(function(data, index) {
        const role = { id: data }
        that.roleIdList.push(role)
      })
    },
    deleteTag(value) {
      userRoles.forEach(function(data, index) {
        if (data.id === value) {
          userRoles.splice(index, value)
        }
      })
    },
    // 新增前将多选的值设置为空
    [CRUD.HOOK.beforeToAdd]() {
      this.roleIdList = []
    },
    /*提交之前处理数据*/
    [CRUD.HOOK.afterValidateCU](crud) {
      if (this.roleIdList.length === 0) {
        this.$message({
          message: '角色不能为空',
          type: 'warning'
        })
        return false
      }
    },
    // 提交前做的操作
    // 改变状态
    changeEnabled(data) {
      this.$confirm('此操作将冻结/解冻 "' + data.userName + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        frozenUser(JSON.stringify(data)).then(res => {
          if (res.state) {
            this.crud.notify('操作成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
          } else {
            appUtils.showError(res.msg)
            data.enabled = !data.enabled
          }
        }).catch(() => {
          data.enabled = !data.enabled
        })
      }).catch(() => {
        data.enabled = !data.enabled
      })
    },
    checkboxT(row, rowIndex) {
      return row.id !== this.user.id
    },
    // /*获取全部角色列表*/
    getAllRoles() {
      getRoleList().then(res => {
        if (res.state) {
          this.roles = res.data
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control, ::v-deep .vue-treeselect__placeholder, ::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
